
import re

def read_ks_file(path):
	with open(path) as stream:
		return read_ks(stream)

def read_ks(stream):
	if stream == '':
		return ([], {}, [])
	if isinstance(stream, basestring):
		text = stream
	else:
		text = stream.read()
	if not isinstance(text, unicode):
		if len(text) >= 2 and text[:2] == '\xff\xfe':
			text = text.decode('utf-16le')[1:]
		else:
			text = text.decode('cp932')
	#text = text.replace(u'\u30fb', u'\xb7')
	lines = re.split(r'[\r\n]+', text.strip())

	assert lines[0] == '*page0|&f.scripttitle'

	script = []
	pages = {}
	i = 0
	for x in join_lines(lines):
		if isinstance(x, int):
			pages[len(script)] = x
		script.append(x)
	actions = []
	return script, pages, lines

def line_to_fun(line):
	assert re.match(r'@\w+', line)
	tokens = line.split()
	return [tokens[0][1:], dict(t.split('=', 2) for t in tokens[1:])]


def join_lines(lines):
	text = ''
	for line in lines:
		if line:
			if line[0] == '*':
				if text:
					yield text
					text = ''
				page  = int(re.match(r'\*page(\d+)', line).group(1))
				yield page
			elif line[0] == '@':
				if text:
					yield text
					text = ''
				yield line_to_fun(line)
			elif line[0] == '[':
				if text:
					yield text
					text = ''
				yield line
			else:
				if '[l]' in line or '[r]' in line:
					yield text + line
					text = ''
				else:
					text += line

	if text:
		yield text


